//
//  YDArchive.m
//  YDBASE
//
//  Created by rowena on 2019/4/27.
//  Copyright © 2019年 wuyezhiguhun. All rights reserved.
//

#import "YDArchive.h"
//Runtime需要的头文件
#import <objc/runtime.h>


@implementation YDArchive


- (instancetype)initWithDict:(NSDictionary *)dict {
    self = [super init];
    if (self) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

+ (instancetype)initWithDict:(NSDictionary *)dict {
    return [[self alloc] initWithDict:dict];
}

#pragma mark ==== KVC 赋值 ====
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    
}
#pragma mark ==== 归档 ====
- (void)encodeWithCoder:(NSCoder *)encoder{
    unsigned int count;
    Ivar *ivar = class_copyIvarList([self class], &count);
    for (int i=0; i<count; i++) {
        Ivar iva = ivar[i];
        const char *name = ivar_getName(iva);
        NSString *strName = [NSString stringWithUTF8String:name];
        //利用KVC取值
        id value = [self valueForKey:strName];
        [encoder encodeObject:value forKey:strName];
    }
    free(ivar);
}

#pragma mark ==== 解档 ====
- (id)initWithCoder:(NSCoder *)decoder {
    
    if (self = [super init]) {
        unsigned int count = 0;
        Ivar *ivar = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i++) {
            Ivar iva = ivar[i];
            const char *name = ivar_getName(iva);
            NSString *strName = [NSString stringWithUTF8String:name];
            //进行解档取值
            id value = [decoder decodeObjectForKey:strName];
            //利用KVC对属性赋值
            [self setValue:value forKey:strName];
            
        }
        free(ivar);
    }
    return self;
}

@end
